<template>
  <div class="ra-mce-editor">
    <editor :id="editorId" v-model="content" :init="editorConfig"></editor>
  </div>
</template>

<script setup>
/**
 * 参考文档：
 * https://gitee.com/wupeng0725/vue3-tinymce
 */
import tinymce from 'tinymce/tinymce';
import Editor from '@tinymce/tinymce-vue';
import { useSettingsStore } from '@/store';
import { ThemeEnum } from '@/enums';

import UploadAPI from '@/api/admin/upload';

import 'tinymce/themes/silver/theme'; // 主题文件
import 'tinymce/icons/default';
import 'tinymce/models/dom';
// tinymce插件可按自己的需要进行导入
import 'tinymce/plugins/accordion'; // 列表插件
import 'tinymce/plugins/lists'; // 列表插件
import 'tinymce/plugins/advlist'; // 有序列表插件
import 'tinymce/plugins/autolink'; // 当用户输入有效的完整URL时，autolink插件会自动创建超链接。
import 'tinymce/plugins/link'; // 链接
import 'tinymce/plugins/autosave'; // 定时自动将编辑内容保存到浏览器本地存储中（Local Storage）
import 'tinymce/plugins/autoresize'; // 可拉伸宽度
import 'tinymce/plugins/charmap'; // 特殊字符
import 'tinymce/plugins/code'; // 查看源码
import 'tinymce/plugins/codesample'; // 插入代码
import 'tinymce/plugins/directionality'; // 文字方向
import 'tinymce/plugins/emoticons'; // 表情符号
import 'tinymce/plugins/emoticons/js/emojis';
import 'tinymce/plugins/fullscreen'; //全屏
import 'tinymce/plugins/image'; // 插入上传图片插件
import 'tinymce/plugins/importcss'; //引入自己定义的css文件
import 'tinymce/plugins/insertdatetime'; //插入时间日期
import 'tinymce/plugins/nonbreaking'; // 空格
import 'tinymce/plugins/pagebreak'; //分页
import 'tinymce/plugins/preview'; // 预览
import 'tinymce/plugins/quickbars'; // 快速工具栏
import 'tinymce/plugins/save'; // 保存
import 'tinymce/plugins/searchreplace'; //查询替换
import 'tinymce/plugins/table'; // 插入表格插件
import 'tinymce/plugins/wordcount'; // 字数统计插件
import 'tinymce/plugins/visualblocks'; // 块范围显示
import { computed } from 'vue';

// 配置项
const settingsStore = useSettingsStore();

// 静态资源路径配置
const tinymceBasePath = './static/tinymce';

// 核心插件引入
const plugins = [
  'lists advlist autolink link autosave charmap code codesample',
  'directionality emoticons image insertdatetime nonbreaking',
  'pagebreak preview quickbars save searchreplace table wordcount',
];

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  height: {
    type: String,
    default: '400',
  },
});

const emit = defineEmits(['update:modelValue']);
const editorId = 'editor' + Date.now();

// 编辑器内容绑定
const content = ref(props.modelValue);

// 图片上传处理
const handleImageUpload = (blobInfo) =>
  new Promise((resolve, reject) => {
    const formData = new FormData();
    formData.append('file', blobInfo.blob());
    formData.append('edit', 1);
    UploadAPI.upload(formData)
      .then(({ data }) => {
        resolve(data.url);
      })
      .catch(reject);
  });

// 切换 亮色 暗色 主题

const skinUrl = computed(() => {
  return settingsStore.theme === ThemeEnum.LIGHT
    ? `${tinymceBasePath}/skins/ui/oxide`
    : `${tinymceBasePath}/skins/ui/oxide-dark`;
});

const contentCss = computed(() => {
  return settingsStore.theme === ThemeEnum.LIGHT
    ? `${tinymceBasePath}/skins/content/default/content.css`
    : `${tinymceBasePath}/skins/content/dark/content.css`;
});

watch(
  () => settingsStore.theme,
  (val) => {
    tinymce.remove();
    editorConfig.skin_url = skinUrl.value;
    editorConfig.content_css = contentCss.value;
    tinymce.init({ ...editorConfig });
  },
);

// 完整编辑器配置
const editorConfig = {
  selector: '#' + editorId,
  license_key: 'gpl',
  height: props.height,
  skin_url: skinUrl.value,
  content_css: contentCss.value,
  language_url: `${tinymceBasePath}/langs/zh_CN.js`,
  language: 'zh_CN',
  plugins: plugins.join(' '),
  toolbar: `undo redo | fontsize | formatselect | bold italic forecolor backcolor |
            alignleft aligncenter alignright | bullist numlist outdent indent |
            link image table emoticons code fullscreen`,

  menubar: false, // 菜单栏
  statusbar: true, // 是否显示底部状态栏
  auto_focus: true, // 自动聚焦
  branding: false, // 默认会在右下角显示Tiny图标
  promotion: false, // 隐藏upgrade按钮
  resize: true, // 改变宽高

  autoresize_bottom_margin: 50,
  automatic_uploads: true,
  images_upload_handler: handleImageUpload,
  setup: (editor) => {
    initCustomFeatures(editor);
  },
};

// 初始化自定义功能
const initCustomFeatures = (editor) => {
  // // 自定义按钮
  // editor.ui.registry.addButton('customButton', {
  //   text: '定制功能',
  //   onAction: () => alert('自定义功能触发'),
  // });
  // // 自动补全
  // editor.ui.registry.addAutocompleter('specialChars', {
  //   trigger: '#',
  //   minChars: 0,
  //   fetch: () => [
  //     { value: '★', text: '星星' },
  //     { value: '※', text: '注释' },
  //   ],
  //   onAction: (_, __, value) => editor.insertContent(value),
  // });
};

// 生命周期管理
onMounted(() => tinymce.init({}));
onBeforeUnmount(() => tinymce.remove());

// 内容同步
watch(content, (val) => emit('update:modelValue', val));
watch(
  () => props.modelValue,
  (val) => (content.value = val),
);
</script>
<style>
.ra-mce-editor {
  width: 100%;
  margin: 5px;
  padding: 5px;
}
/* 编辑器容器样式 */
:deep(.tox-tinymce) {
  border-radius: 8px;
  transition: border-color 0.3s ease;
}

:deep(.tox-editor-header) {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
